/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.web.query;

import han.bifang.business.domain.ServiceCatalogManager;
import han.bifang.business.query.QueryManager;
import han.bifang.common.entity.BusBindingWrapper;
import han.bifang.common.entity.CatalogBindingWrapper;
import han.bifang.common.entity.EntityConstants;
import han.bifang.common.entity.MappingServiceDetailInfo;
import han.bifang.common.entity.MappingServiceVersionDetailInfo;
import han.bifang.common.entity.ServiceBusDetailInfo;
import han.bifang.common.entity.ServiceDetailInfo;
import han.bifang.common.entity.SoaCatalogDetail;
import han.bifang.common.entity.SoaHttpBinding;
import han.bifang.common.entity.SoaJmsBindingWrapper;
import han.bifang.common.entity.SoaMethodQos;
import han.bifang.common.entity.SoaMqJms;
import han.bifang.common.entity.SoaNormalJms;
import han.bifang.common.entity.SoaServiceQos;
import han.bifang.common.entity.SoaSoapBinding;
import han.bifang.common.entity.SoaVersionQos;
import han.bifang.common.entity.SoaWebServicesMethodWrapper;
import han.bifang.common.entity.SoaWsdlWrapper;
import han.bifang.common.entity.VersionDetailInfo;
import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import v1.query.web.bifang.han.MappingServiceDocument;
import v1.query.web.bifang.han.QueryResponseDocument;
import v1.query.web.bifang.han.ServiceBusDocument;
import v1.query.web.bifang.han.ServiceCatDocument;
import v1.query.web.bifang.han.ServiceDocument;
import v1.query.web.bifang.han.BusBindingDocument.BusBinding;
import v1.query.web.bifang.han.CatBindingDocument.CatBinding;
import v1.query.web.bifang.han.HttpBindingDocument.HttpBinding;
import v1.query.web.bifang.han.JmsBindingDocument.JmsBinding;
import v1.query.web.bifang.han.JmsBindingDocument.JmsBinding.Info;
import v1.query.web.bifang.han.MappingServiceVersionDocument.MappingServiceVersion;
import v1.query.web.bifang.han.MethodParamDocument.MethodParam;
import v1.query.web.bifang.han.MqJmsDocument.MqJms;
import v1.query.web.bifang.han.NormalJmsDocument.NormalJms;
import v1.query.web.bifang.han.QosDocument.Qos;
import v1.query.web.bifang.han.SoapBindingDocument.SoapBinding;
import v1.query.web.bifang.han.VersionDocument.Version;
import v1.query.web.bifang.han.VersionDocument.Version.Binding;
import v1.query.web.bifang.han.WebServicesBindingDocument.WebServicesBinding;
import v1.query.web.bifang.han.WebServicesMethodDocument.WebServicesMethod;

/**
 * 
 * @Author Kent
 */
public class QueryHelper {

	public static QueryResponseDocument queryService(String code)
			throws BifangException {
		QueryResponseDocument res = QueryResponseDocument.Factory.newInstance();
		try {

			ServiceDetailInfo info = QueryManager.getServiceDetailByCode(code);
			if (info != null) {
				ServiceDocument doc = ServiceDocument.Factory.newInstance();

				doc.addNewService();
				BeanUtils.copyProperties(doc.getService(), info.getService());
				for (String id : info.getBusRel()) {
					doc.getService().addBusRel(id);
				}
				for (SoaServiceQos qos : info.getQos()) {
					Qos qdoc = doc.getService().addNewQos();
					qdoc.setName(qos.getName());
					if (qos.getName().equals(EntityConstants.QOS_WARN_ERROR)
							|| qos.getName().equals(
									EntityConstants.QOS_WARN_RESPONSE_TIME)) {
						qdoc.setValue("<!--" + qos.getValue() + "-->");
					} else {
						qdoc.setValue(qos.getValue());
					}

				}
				for (VersionDetailInfo v : info.getVersions()) {
					Version v1 = doc.getService().addNewVersion();
					v1.setBindingType(v.getVersion().getBindingType());
					v1.setStatus(v.getVersion().getStatus());
					v1.setVersion(v.getVersion().getVersion());

					for (SoaVersionQos qos : v.getQos()) {
						Qos qdoc = v1.addNewQos();
						qdoc.setName(qos.getName());
						if (qos.getName()
								.equals(EntityConstants.QOS_WARN_ERROR)
								|| qos.getName().equals(
										EntityConstants.QOS_WARN_RESPONSE_TIME)) {
							qdoc.setValue("<!--" + qos.getValue() + "-->");
						} else {
							qdoc.setValue(qos.getValue());
						}
					}

					Binding b = v1.addNewBinding();
					if (v1.getBindingType()
							.equals(EntityConstants.BINDING_HTTP)) {
						HttpBinding hb = b.addNewHttpBinding();
						SoaHttpBinding shb = (SoaHttpBinding) v.getBinding();
						BeanUtils.copyProperties(hb, shb);
					} else if (v1.getBindingType().equals(
							EntityConstants.BINDING_SOAP)) {
						SoapBinding hb = b.addNewSoapBinding();
						SoaSoapBinding shb = (SoaSoapBinding) v.getBinding();
						BeanUtils.copyProperties(hb, shb);
					} else if (v1.getBindingType().equals(
							EntityConstants.BINDING_JMS)) {
						JmsBinding jb = b.addNewJmsBinding();
						SoaJmsBindingWrapper w = (SoaJmsBindingWrapper) v
								.getBinding();
						BeanUtils.copyProperties(jb, w.getJmsBinding());
						Info in = jb.addNewInfo();
						if (jb.getServer().equals("WebSphere MQ")) {
							MqJms mq = in.addNewMqJms();
							SoaMqJms sm = (SoaMqJms) w.getInfo();
							BeanUtils.copyProperties(mq, sm);
						} else {
							NormalJms j = in.addNewNormalJms();
							SoaNormalJms sj = (SoaNormalJms) w.getInfo();
							BeanUtils.copyProperties(j, sj);
						}
					} else if (v1.getBindingType().equals(
							EntityConstants.BINDING_WEB_SERVICES)) {
						WebServicesBinding wb = b.addNewWebServicesBinding();
						SoaWsdlWrapper ww = (SoaWsdlWrapper) v.getBinding();
						wb.setEndpointUrl(ww.getWebServicesBinding()
								.getEndpointUrl());
						wb.setName(ww.getWebServicesBinding().getName());
						wb.setNamespace(ww.getWebServicesBinding()
								.getNamespace());
						wb.setSoapVersion(ww.getWebServicesBinding()
								.getSoapVersion());
						wb.setWsdlUrl(ww.getWebServicesBinding().getWsdlUrl());

						for (int i = 0, j = ww.getMethods().size(); i < j; i++) {
							SoaWebServicesMethodWrapper wmw = (SoaWebServicesMethodWrapper) ww
									.getMethods().get(i);
							WebServicesMethod wm = wb.addNewWebServicesMethod();
							BeanUtils.copyProperties(wm, wmw.getMethod());
							for (int i1 = 0, j1 = wmw.getQos().size(); i1 < j1; i1++) {
								SoaMethodQos mqos = (SoaMethodQos) wmw.getQos()
										.get(i1);
								Qos qdoc = wm.addNewQos();
								qdoc.setName(mqos.getName());
								if (mqos.getName().equals(
										EntityConstants.QOS_WARN_ERROR)
										|| mqos
												.getName()
												.equals(
														EntityConstants.QOS_WARN_RESPONSE_TIME)) {
									qdoc.setValue("<!--" + mqos.getValue()
											+ "-->");
								} else {
									qdoc.setValue(mqos.getValue());
								}
							}
							MethodParam mp = wm.addNewMethodParam();
							BeanUtils.copyProperties(mp, wmw.getParams());

						}
					}
				}
				res.addNewQueryResponse().addNewResult().setService(
						doc.getService());

			} else {
				MappingServiceDetailInfo minfo = QueryManager
						.getMappingServiceDetailByCode(code);
				if (minfo != null) {
					MappingServiceDocument doc = MappingServiceDocument.Factory
							.newInstance();
					doc.addNewMappingService();
					BeanUtils.copyProperties(doc.getMappingService(), minfo
							.getService());
					for (SoaServiceQos qos : minfo.getQos()) {
						Qos q = doc.getMappingService().addNewQos();
						q.setName(qos.getName());
						q.setValue("<!--" + qos.getValue() + "-->");
					}
					for (String id : minfo.getBusRel()) {
						doc.getMappingService().addBusRel(id);
					}

					for (MappingServiceVersionDetailInfo v : minfo
							.getVersions()) {
						MappingServiceVersion vv = doc.getMappingService()
								.addNewMappingServiceVersion();
						vv.setVersion(v.getVersion().getVersion());
						for (SoaVersionQos qos : v.getQos()) {
							Qos q = vv.addNewQos();
							q.setName(qos.getName());
							q.setValue("<!--" + qos.getValue() + "-->");
						}
					}
					res.addNewQueryResponse().addNewResult().setMappingService(
							doc.getMappingService());
				} else {
					res.addNewQueryResponse().addNewError().setErrorCode(
							BifangErrorCode.SERVICE_CODE_EXISTS_ERROR);
					res.getQueryResponse().getError().setErrorMsg(
							"No such service code [" + code + "]");
				}

			}

		} catch (BifangException e) {
			Log logger = LogFactory.getLog(QueryHelper.class);
			logger.error("QueryHelper.queryService()", e);
			res.addNewQueryResponse().addNewError().setErrorCode(e.getCode());
			res.getQueryResponse().getError().setErrorMsg(e.getMsg());
		} catch (Exception e) {
			Log logger = LogFactory.getLog(QueryHelper.class);
			logger.error("QueryHelper.queryService()", e);
			res.addNewQueryResponse().addNewError().setErrorCode(
					BifangErrorCode.UNKNOWN_ERROR);
			res.getQueryResponse().getError().setErrorMsg(
					"error : " + e.getMessage());
		}
		return res;

	}

	public static QueryResponseDocument queryServiceBus(String id, String code)
			throws BifangException {
		QueryResponseDocument res = QueryResponseDocument.Factory.newInstance();
		try {
			ServiceBusDetailInfo info = null;
			if (id != null) {
				info = QueryManager.getServiceBusDetailById(id);
			} else {
				info = QueryManager.getServiceBusDetailByCode(code);
			}
			if (info != null) {
				ServiceBusDocument doc = ServiceBusDocument.Factory
						.newInstance();
				doc.addNewServiceBus();
				doc.getServiceBus().setNotifyServiceCode(
						info.getNotifyServiceCode());
				doc.getServiceBus().setNotifyServiceVersion(
						info.getNotifyServiceVersion());
				doc.getServiceBus().setAppServer(info.getBus().getAppServer());
				doc.getServiceBus().setCode(info.getBus().getCode());
				doc.getServiceBus().setServerVersion(
						info.getBus().getServerVersion());
				doc.getServiceBus().setId(info.getBus().getId());

				for (BusBindingWrapper w : info.getBindings()) {
					BusBinding b = doc.getServiceBus().addNewBusBinding();
					b.setName(w.getBusBinding().getName());
					b.setType(w.getBusBinding().getType());

					if (b.getType().equals(EntityConstants.BINDING_HTTP)) {
						HttpBinding hb = b.addNewBinding().addNewHttpBinding();
						SoaHttpBinding shb = w.getHttpBinding();
						BeanUtils.copyProperties(hb, shb);
					} else if (b.getType().equals(EntityConstants.BINDING_SOAP)) {
						SoapBinding hb = b.addNewBinding().addNewSoapBinding();
						SoaSoapBinding shb = w.getSoapBinding();
						BeanUtils.copyProperties(hb, shb);
					} else if (b.getType().equals(EntityConstants.BINDING_JMS)) {
						JmsBinding jb = b.addNewBinding().addNewJmsBinding();
						SoaJmsBindingWrapper jw = w.getJmsBinding();
						BeanUtils.copyProperties(jb, jw.getJmsBinding());
						Info in = jb.addNewInfo();
						if (jb.getServer().equals("WebSphere MQ")) {
							MqJms mq = in.addNewMqJms();
							SoaMqJms sm = (SoaMqJms) jw.getInfo();
							BeanUtils.copyProperties(mq, sm);
						} else {
							NormalJms j = in.addNewNormalJms();
							SoaNormalJms sj = (SoaNormalJms) jw.getInfo();
							BeanUtils.copyProperties(j, sj);
						}
					} else if (b.getType().equals(
							EntityConstants.BINDING_WEB_SERVICES)) {
						SoapBinding hb = b.addNewBinding().addNewSoapBinding();
						SoaSoapBinding shb = w.getSoapBinding();
						BeanUtils.copyProperties(hb, shb);

					}

				}
				res.addNewQueryResponse().addNewResult().setServiceBus(
						doc.getServiceBus());
			} else {
				res.addNewQueryResponse().addNewError().setErrorCode(
						BifangErrorCode.SERVICE_BUS_NOT_EXISTS_ERROR);
				res.getQueryResponse().getError().setErrorMsg(
						"No such service bus id [" + code + "]");
			}

		} catch (BifangException e) {
			Log logger = LogFactory.getLog(QueryHelper.class);
			logger.error("QueryHelper.queryServiceBus()", e);
			res.addNewQueryResponse().addNewError().setErrorCode(e.getCode());
			res.getQueryResponse().getError().setErrorMsg(e.getMsg());
		} catch (Exception e) {
			Log logger = LogFactory.getLog(QueryHelper.class);
			logger.error("QueryHelper.queryServiceBus()", e);
			res.addNewQueryResponse().addNewError().setErrorCode(
					BifangErrorCode.UNKNOWN_ERROR);
			res.getQueryResponse().getError().setErrorMsg(
					"error : " + e.getMessage());
		}
		return res;
	}

	public static QueryResponseDocument queryDefaultServiceCatalog()
			throws BifangException {
		QueryResponseDocument res = QueryResponseDocument.Factory.newInstance();
		try {
			SoaCatalogDetail info = null;
			info = ServiceCatalogManager.getDefaultServiceCatalogDetail();
			
			if (info != null) {
				ServiceCatDocument doc = ServiceCatDocument.Factory
						.newInstance();
				doc.addNewServiceCat();
				doc.getServiceCat().setAppServer(info.getServiceCatalog().getAppServer());
				doc.getServiceCat().setCode(info.getServiceCatalog().getCode());
				doc.getServiceCat().setServerVersion(
						info.getServiceCatalog().getServerVersion());
				doc.getServiceCat().setId(info.getServiceCatalog().getId());

				for (CatalogBindingWrapper w : info.getBindings()) {
					CatBinding b = doc.getServiceCat().addNewCatBinding();
					b.setName(w.getCatalogBinding().getName());
					b.setType(w.getCatalogBinding().getType());

					if (b.getType().equals(EntityConstants.BINDING_HTTP)) {
						HttpBinding hb = b.addNewBinding().addNewHttpBinding();
						SoaHttpBinding shb = w.getHttpBinding();
						BeanUtils.copyProperties(hb, shb);
					} else if (b.getType().equals(EntityConstants.BINDING_SOAP)) {
						SoapBinding hb = b.addNewBinding().addNewSoapBinding();
						SoaSoapBinding shb = w.getSoapBinding();
						BeanUtils.copyProperties(hb, shb);
					} else if (b.getType().equals(EntityConstants.BINDING_JMS)) {
						JmsBinding jb = b.addNewBinding().addNewJmsBinding();
						SoaJmsBindingWrapper jw = w.getJmsBinding();
						BeanUtils.copyProperties(jb, jw.getJmsBinding());
						Info in = jb.addNewInfo();
						if (jb.getServer().equals("WebSphere MQ")) {
							MqJms mq = in.addNewMqJms();
							SoaMqJms sm = (SoaMqJms) jw.getInfo();
							BeanUtils.copyProperties(mq, sm);
						} else {
							NormalJms j = in.addNewNormalJms();
							SoaNormalJms sj = (SoaNormalJms) jw.getInfo();
							BeanUtils.copyProperties(j, sj);
						}
					} else if (b.getType().equals(
							EntityConstants.BINDING_WEB_SERVICES)) {
						SoapBinding hb = b.addNewBinding().addNewSoapBinding();
						SoaSoapBinding shb = w.getSoapBinding();
						BeanUtils.copyProperties(hb, shb);

					}

				}
				res.addNewQueryResponse().addNewResult().setServiceCat(
						doc.getServiceCat());
			} else {
				res.addNewQueryResponse().addNewError().setErrorCode(
						BifangErrorCode.SERVICE_BUS_NOT_EXISTS_ERROR);
				res.getQueryResponse().getError().setErrorMsg(
						"No default service catalog, please create service catalog in local domain ");
			}

		} catch (BifangException e) {
			Log logger = LogFactory.getLog(QueryHelper.class);
			logger.error("QueryHelper.queryServiceCat()", e);
			res.addNewQueryResponse().addNewError().setErrorCode(e.getCode());
			res.getQueryResponse().getError().setErrorMsg(e.getMsg());
		} catch (Exception e) {
			Log logger = LogFactory.getLog(QueryHelper.class);
			logger.error("QueryHelper.queryServiceCat()", e);
			res.addNewQueryResponse().addNewError().setErrorCode(
					BifangErrorCode.UNKNOWN_ERROR);
			res.getQueryResponse().getError().setErrorMsg(
					"error : " + e.getMessage());
		}
		return res;
	}

}
